﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JXT.PrimaryKey.Batman.Cache;
using JXT.PrimaryKey.Batman.Core.Cache;
using JXT.PrimaryKey.Batman.Domain.Services;
using JXT.PrimaryKey.Batman.Domain.Quotation.Models;
using JXT.PrimaryKey.Batman.Domain.Quotation.Repositories;

namespace JXT.PrimaryKey.Batman.Domain.Quotation.Services.Default
{
    public class SecuritiesService : CachedServiceBase<Securities>, ISecuritiesService
    {
        private ICache _httpCache = new HttpCache();

        public void Save(Securities entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            LoadRepository<ISecuritiesRepository>().Add(entity);
            _httpCache.Remove(buildCacheKey(entity.MarketType));
        }

        public Securities GetSingle(string code, MarketType marketType = MarketType.Unknown)
        {
            //return LoadRepository<ISecuritiesRepository>().GetSingle(code, marketType);
            return GetList(marketType).FirstOrDefault(e => e.Code.Equals(code, StringComparison.InvariantCultureIgnoreCase));
        }

        public IEnumerable<Securities> SearchList(string code, int num, MarketType marketType = MarketType.Unknown, SecuritiesType securitiesType = SecuritiesType.Unknown)
        {
            return LoadRepository<ISecuritiesRepository>().SearchList(code, num, marketType,securitiesType);
            //return GetList(marketType).Where(e => e.Code.Equals(code, StringComparison.InvariantCultureIgnoreCase)).Take(num);
        }

        public IEnumerable<Securities> GetList(MarketType market = MarketType.Unknown)
        {
            //if (market == MarketType.Unknown)
            //    return LoadRepository<ISecuritiesRepository>().GetList(market).ToList();
            var cacheKey = buildCacheKey(market);
            var list = _httpCache.Get(cacheKey) as List<Securities>;
            if (list == null)
            {
                list = LoadRepository<ISecuritiesRepository>().GetList(market).ToList();
                _httpCache.Add(cacheKey, list, TimeSpan.FromMinutes(15));
            }
            return list;
        }

        private string buildCacheKey(MarketType type)
        {
            return String.Format("{0}_{1}", CacheSpace, type);
        }

        public override void ClearCache()
        {
            base.ClearCache();
            Cache.Remove(buildCacheKey(MarketType.Unknown));
            Cache.Remove(buildCacheKey(MarketType.Hongkong));
            Cache.Remove(buildCacheKey(MarketType.Shanghai));
            Cache.Remove(buildCacheKey(MarketType.Shenzhen));
        }
    }
}
